package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.google.gson.Gson;
import com.heima.api.ArticleClient;
import com.heima.api.TaskClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.task.TaskConstans;
import com.heima.model.wemedia.dtos.TextAndImgeUrls;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
import org.apache.logging.log4j.core.util.JsonUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    private final GreenTextScan greenTextScan;
    private final GreenImageScan greenImageScan;
    private final FileStorageService fileStorageService;
    private final WmNewsMapper wmNewsMapper;
    private final WmUserService wmUserService;
    private final WmChannelService wmChannelService;
    private final ArticleClient articleClient;
    private final WmSensitiveMapper wmSensitiveMapper;
    private final Tess4jClient tess4jClient;
    private final KafkaTemplate<String, String> kafkaTemplate;
    private final TaskClient taskClient;

    /**
     * 文章自动审核
     *
     * @param wmNews
     */
    @Override
    @Async
    @GlobalTransactional
    public void autoScan(WmNews wmNews) {
        System.err.println("线程池线程执行中:" + Thread.currentThread().getName());
        //1.获取文章图文信息
        TextAndImgeUrls textAndImages = getTextAndImages(wmNews);
        //文本(含标题)和图片文字铭感词审核
        if (!scanSensitive(wmNews, textAndImages)) {
            return;
        }
        //2.文章文本审核(含标题)
        String text = textAndImages.getText();
        if (!scanText(text, wmNews)) {
            //文本审核失败 修改文章信息
            wmNewsMapper.updateById(wmNews);
            log.info("审核失败！");
            return;
        }
        //3.文章图片审核(含封面)
        List<String> urls = textAndImages.getUrls();
        if (!ObjectUtils.isEmpty(urls)) {
            if (!scanImages(urls, wmNews)) {
                //图片审核失败   修改文章信息
                wmNewsMapper.updateById(wmNews);
                log.info("审核失败！");
                return;
            }
        }
        //审核成功
        wmNewsMapper.updateById(wmNews);
        log.info("审核通过！！！");
        //4.如果发布时间为不null,则添加到定时任务
        if (wmNews.getPublishTime() != null) {
            log.info("文章设置了定时发布,需要添加到延迟任务中!");
            Task task = new Task();
            task.setTaskType(TaskConstans.Publish_Task_Type);
            task.setExecuteTime(wmNews.getPublishTime());
            task.setPriority(1);
            task.setParameters(JSON.toJSONString(wmNews));
            taskClient.addTask(task);
            return;
        }

        //-----审核通过,发布文章
        publishNews(wmNews);
        //通知app生成文章详情
        kafkaTemplate.send("apArticleGenerate-topic", wmNews.getArticleId().toString());

    }

    @Override
    public void schedulePublishNews(WmNews wmNews) {
        //-----审核通过,发布文章
        publishNews(wmNews);
        //通知app生成文章详情
        kafkaTemplate.send("apArticleGenerate-topic", wmNews.getArticleId().toString());
    }
    /**
     * 发布文章
     *
     * @param wmNews
     */
    private void publishNews(WmNews wmNews) {
        //1.封装文章信息  //authorId  authorName channelName layout   publishTime:重新设置
        ApArticleDto apArticleDto = new ApArticleDto();
        BeanUtils.copyProperties(wmNews, apArticleDto);
        //获取作者信息
        apArticleDto.setAuthorId(wmNews.getUserId());
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        apArticleDto.setAuthorName(wmUser.getNickname());
        //获取频道名称
        WmChannel wmChannel = wmChannelService.getById(wmNews.getChannelId());
        apArticleDto.setChannelName(wmChannel.getName());
        //获取文章布局  0 无图文章   1 单图文章    3 多图文章
        apArticleDto.setLayout(wmNews.getType());
        //2.远程调用文章微服务发布文章，并返回文章id
        apArticleDto.setId(null);
        ApArticle apArticle = articleClient.saveArticle(apArticleDto);
        //3.修改文章库文章状态
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(apArticle.getId());
        wmNews.setPublishTime(apArticle.getPublishTime());
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 敏感词审核(包含图片文字)
     *
     * @param wmNews
     * @param textAndImages
     * @return
     */
    private boolean scanSensitive(WmNews wmNews, TextAndImgeUrls textAndImages) {
        //获取图片中的文字
        List<String> urls = textAndImages.getUrls();
        StrBuilder imagesText = new StrBuilder("");
        try {
            if (!ObjectUtils.isEmpty(urls)) {
                for (String url : urls) {
                    byte[] bytes = fileStorageService.downLoadFile(url);
                    //从byte[]转换为butteredImage
                    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                    BufferedImage imageFile = ImageIO.read(in);
                    //识别图片的文字
                    String imageText = tess4jClient.doOCR(imageFile);
                    imagesText.append("-").append(imageText);
                }
                log.info("图片文字:" + imagesText.toString());
            }
        } catch (Exception e) {
            log.info("图片文字识别失败,转人工审核！");
            wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
            wmNewsMapper.updateById(wmNews);
            return false;
        }
        //文本和图片文字合并
        String text = textAndImages.getText() + "-" + imagesText.toString();
        if (!scanSensitiveAllText(text)) {
            //文本或图片中包含敏感词，审核失败
            wmNews.setStatus(WmNews.Status.FAIL.getCode());
            //文本审核失败 修改文章信息
            wmNewsMapper.updateById(wmNews);
            log.info("审核失败！");
            return false;
        }
        return true;
    }

    /**
     * 敏感词审核
     *
     * @param text
     */
    private Boolean scanSensitiveAllText(String text) {
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
        if (ObjectUtils.isEmpty(wmSensitives)) {
            log.info("敏感词为空,不审核敏感词！");
            return true;
        }
        //获取敏感词集合
        List<String> list = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(list);
        //匹配敏感词
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(text);
        if (!ObjectUtils.isEmpty(stringIntegerMap)) {
            //敏感词审核不通过
            log.info("敏感词:" + stringIntegerMap);
            log.info("敏感词审核不通过！");
            return false;
        }
        return true;
    }

    /**
     * 文本审核
     *
     * @param text
     * @throws Exception
     */
    private Boolean scanText(String text, WmNews wmNews) {
        try {
            Map map = greenTextScan.greeTextScan(text);
            return isSucess(wmNews, map);
        } catch (Exception e) {
            log.error("文字审核异常,走人工审核", e);
            wmNews.setStatus(WmNews.Status.ADMIN_SUCCESS.getCode());
            return false;
        }
    }

    /**
     * 图片审核
     *
     * @param urls
     * @throws Exception
     */
    private Boolean scanImages(List<String> urls, WmNews wmNews) {
        try {
            ArrayList<byte[]> images = new ArrayList<>();
            for (String url : urls) {
                byte[] bytes = fileStorageService.downLoadFile(url);
                images.add(bytes);
            }
            Map map = greenImageScan.imageScan(images);
            return isSucess(wmNews, map);
        } catch (Exception e) {
            log.error("图片审核异常,走人工审核", e);
            wmNews.setStatus(WmNews.Status.ADMIN_SUCCESS.getCode());
            return false;
        }

    }

    private static Boolean isSucess(WmNews wmNews, Map map) {
        if (map == null) {
            log.error("阿里云接口图文审核异常,走人工审核");
            wmNews.setStatus(WmNews.Status.ADMIN_SUCCESS.getCode());
            return false;
        }
        if ("pass".equals(map.get("suggestion"))) {
            //通过审核
            wmNews.setStatus(WmNews.Status.SUCCESS.getCode());
            return true;
        } else {
            //未通过审核，拒绝审核
            log.info("审核失败，拒绝审核！");
            wmNews.setStatus(WmNews.Status.FAIL.getCode());
            //设置审核失败原因
            wmNews.setReason(map.get("label").toString());
            return false;
        }
    }


    /**
     * 获获取文章图文信息
     *
     * @param wmNews
     */
    private TextAndImgeUrls getTextAndImages(WmNews wmNews) {
        //获取图片集合
        String content = wmNews.getContent();
        List<String> imageUrls = new ArrayList<>();
        JSONArray jsonArray = JSON.parseArray(content);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if ("image".equals(jsonObject.getString("type"))) {
                imageUrls.add(jsonObject.getString("value"));
            }
        }
        //获取封面
        String coverImages = wmNews.getImages();
        if (!"".equals(coverImages) && coverImages != null) {
            // 使用split方法按逗号拆分字符串
            String[] coverImageArry = coverImages.split(",");
            // 将拆分后的字符串数组转换为List
            List<String> coverImageList = new ArrayList<>(Arrays.asList(coverImageArry));
            imageUrls.addAll(coverImageList);
        }
        //图片去重
        List<String> allUrls = imageUrls.stream().distinct().collect(Collectors.toList());

        //获取文本内容
        StrBuilder text = new StrBuilder();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if ("text".equals(jsonObject.getString("type"))) {
                text.append(jsonObject.getString("value"));
            }
        }
        //获取标题
        text.append("-").append(wmNews.getTitle());
        //封装图文信息
        TextAndImgeUrls textAndImgeUrls = new TextAndImgeUrls();
        textAndImgeUrls.setText(text.toString());
        textAndImgeUrls.setUrls(allUrls);
        return textAndImgeUrls;
    }
}
